import 'dart:typed_data';

import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:share_extend/share_extend.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/utils/_.dart';

class TileWidget extends StatefulWidget {
  TileWidget({Key? key, required this.thinkData}) : super(key: key);

  final Think thinkData;

  @override
  _TileWidget createState() => _TileWidget(thinkData: thinkData);
}

class _TileWidget extends State<TileWidget>
    with SingleTickerProviderStateMixin {
  _TileWidget({required this.thinkData});

  Think? thinkData;
  AnimationController? _animationController;
  dynamic _iconAnimation;
  late bool isLike;

  @override
  void initState() {
    super.initState();

    setLikeIconAnimated();
    this.isLike = thinkData!.isLike!;
    setState(() {});
  }

  @override
  void dispose() {
    _animationController!.dispose();
    super.dispose();
  }

  /// 保存图片到相册
  saveGallery(String url) async {
    var response = await PublicService.downImage(url: url, params: {});
    String fileName = Tool.randomBit();
    final result = await ImageGallerySaver.saveImage(
        Uint8List.fromList(response),
        quality: 100,
        name: fileName
    );
    result['isSuccess']
        ? BotToast.showText( text: '图片存储在 ${result['filePath']}')
        : BotToast.showText( text:"保存失败");
  }

  /// 分享给好友
  shareImg() async {
    ShareExtend.share(
      "[有人@你]\n最牛的人文app\n\napp下载地址：http://192.168.31.202:4001/app/thinking.apk",
      "text",
      sharePanelTitle: "thinking",
    );
  }

  Future<void> collectionThisThink() async {

    setState(() {
      thinkData!.setIsCollection = !thinkData!.isCollection!;
      if (thinkData!.isCollection!) {
        thinkData!.setThinkCollectionType = thinkData!.thinkCollectionType! + 1;
      } else {
        thinkData!.setThinkCollectionType = thinkData!.thinkCollectionType! - 1;
      }
    });

    await HomeService.isCollectionThink(params: {
      'isCollection': thinkData!.isCollection,
      'user_Id': SPreferences().getInt('user_Id'),
      'think_Id': thinkData!.id
    });
    if (thinkData!.isCollection!) BotToast.showText(text: '收藏成功');
  }

  Future<void> likeThisThink() async {
    if (_iconAnimation.status == AnimationStatus.forward ||
        _iconAnimation.status == AnimationStatus.reverse) {
      return;
    }
    setState(() {
      this.isLike = !this.isLike;
      thinkData!.setIsLike = this.isLike;
      if (this.isLike) {
        thinkData!.setThinkLikeType = thinkData!.thinkLikeType! + 1;
      } else {
        thinkData!.setThinkLikeType = thinkData!.thinkLikeType! - 1;
      }
    });
    if (_iconAnimation.status == AnimationStatus.dismissed) {
      _animationController!.forward();
    } else if (_iconAnimation.status == AnimationStatus.completed) {
      _animationController!.reverse();
    }
    await HomeService.isLikeThink(params: {
      'isLike': this.isLike,
      'user_Id': SPreferences().getInt('user_Id'),
      'think_Id': thinkData!.id
    });
    if (this.isLike) BotToast.showText(text: '点赞成功');
  }

  void setLikeIconAnimated() {
    _animationController =
        AnimationController(duration: Duration(milliseconds: 300), vsync: this);
    _iconAnimation = TweenSequence([
      TweenSequenceItem(
          tween: Tween(begin: 1.0, end: 1.3)
              .chain(CurveTween(curve: Curves.easeIn)),
          weight: 50),
      TweenSequenceItem(tween: Tween(begin: 1.3, end: 1.0), weight: 50),
    ]).animate(_animationController!);
  }

  @override
  Widget build(BuildContext context) {
    return thinkData!.thinkStatus == 1
        ? GestureDetector(
      onTap: (){
        if(thinkData!.thinkCategory != 1){
          Modular.to.pushNamed('/thinkInfo/${thinkData!.id}/${thinkData!.thinkCategory}');
        }
      },
      child: Container(
        child: Stack(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(10)),
              child: CachedNetworkImage(
                imageUrl: thinkData!.thinkIndexImageUrl!,
                fit: BoxFit.cover,
                width: (Screen.width(Config.context) - 12) / 2,
                errorWidget: (context, url, error) => new Icon(Icons.error),
                placeholder: (context, url) => Container(
                  width: Screen.setWidth(60),
                  height: Screen.setWidth(60),
                  child: Center(
                    child: CircularProgressIndicator(),
                  ),
                ),
              ),
            ),
            Positioned(
              bottom: 0,
              child: ClipRRect(
                borderRadius:
                BorderRadius.vertical(bottom: Radius.circular(10)),
                child: Container(
                  padding: EdgeInsets.fromLTRB(10, 4, 10, 6),
                  height: Screen.setHeight(70),
                  width: (Screen.width(Config.context) - 12) / 2,
                  decoration: BoxDecoration(color: Colors.black45),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Container(
                              child: Text(
                                thinkData!.thinkTitle!,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 17,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w600),
                              ),
                            ),
                          ),
                          GestureDetector(
                            onTap: () async {
                              await showDialog(
                                  context: context,
                                  builder: (context) {
                                return SimpleDialog(
                                  titlePadding: EdgeInsets.all(15),
                                  contentPadding: EdgeInsets.all(15),
                                  title: Container(
                                    alignment: Alignment.centerLeft,
                                    child: Row(
                                      children: [
                                        Icon(Icons.touch_app,size: 30,color: ColorConfig.ThemeColor,),
                                        SizedBox(width: 5,),
                                        Text("请选择操作",style: TextStyle(fontSize: 17),)
                                      ],
                                    ),
                                  ),
                                  children: <Widget>[
                                    TextButton(
                                        child: Text("保存到相册",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                        onPressed: () async {
                                          Navigator.of(context).pop();
                                          await saveGallery(thinkData!.thinkIndexImageUrl!
                                          );
                                        }
                                    ),
                                    TextButton(
                                        child: Text("收藏",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                        onPressed: () async {
                                          Navigator.of(context).pop();
                                          await collectionThisThink(
                                          );
                                        }
                                    ),
                                    TextButton(
                                        child: Text("分享",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                        onPressed: () async {
                                          Navigator.of(context).pop();
                                          await shareImg(
                                          );
                                        }
                                    ),

                                  ],
                                );
                              }
                              );
                            },
                            child: Icon(
                              Icons.more_vert,
                              color: ColorConfig.WhiteObsBackColor,
                              size: 20,
                            ),
                          )
                        ],
                      ),
                      thinkData!.thinkCategory !=0
                          ? Row(
                        children: [
                          ClipOval(
                            child: GestureDetector(
                              onTap: () {
                                print(thinkData!.id);
                              },
                              child: ClipRRect(
                                child: CachedNetworkImage(
                                  imageUrl:
                                  thinkData!.thinkUserImage!,
                                  fit: BoxFit.cover,
                                  width: Screen.setWidth(28),
                                  height: Screen.setWidth(28),
                                  errorWidget:
                                      (context, url, error) =>
                                  new Icon(Icons.error),
                                  placeholder: (context, url) =>
                                      Container(
                                        width: Screen.setWidth(20),
                                        height: Screen.setWidth(20),
                                        color: ColorConfig.ThemeColor,
                                      ),
                                ),
                              ),
                            ),
                          ),
                          SizedBox(
                            width: Screen.setWidth(4),
                          ),
                          Expanded(
                            child: Text(
                              thinkData!.thinkCountry!.name! +
                                  '-' +
                                  thinkData!.thinkTimes!,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: 13,
                                  color:
                                  ColorConfig.WhiteObsBackColor),
                            ),
                          ),
                          SizedBox(
                            width: Screen.setWidth(4),
                          ),
                          Text(
                              thinkData!.thinkLikeType! <= 999
                                  ? thinkData!.thinkLikeType!
                                  .toString()
                                  : thinkData!.thinkLikeType! >= 10000
                                  ? '${thinkData!.thinkLikeType! ~/ 10000}w+'
                                  : '${thinkData!.thinkLikeType! ~/ 1000}k+',
                              style: TextStyle(
                                  fontSize: 14,
                                  color: this.isLike
                                      ? ColorConfig.ThemeColor
                                      : ColorConfig
                                      .WhiteObsBackColor)),
                          SizedBox(
                            width: Screen.setWidth(4),
                          ),
                          GestureDetector(
                            onTap: () {
                              likeThisThink();
                            },
                            child: ScaleTransition(
                              scale: _iconAnimation,
                              child: this.isLike
                                  ? Icon(
                                CupertinoIcons.heart_fill,
                                size: 25,
                                color: ColorConfig.ThemeColor,
                              )
                                  : Icon(
                                CupertinoIcons.heart,
                                size: 25,
                                color: ColorConfig
                                    .WhiteObsBackColor,
                              ),
                            ),
                          )
                        ],
                      )
                          : Row(
                        children: [
                          Expanded(
                            child: Text(
                              thinkData!.thinkCountry!.name! +
                                  ' - ' +
                                  thinkData!.thinkTime!.timeTitle! +
                                  ' - ' +
                                  thinkData!.thinkTimes!,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: 13,
                                  color:
                                  ColorConfig.WhiteObsBackColor),
                            ),
                          ),
                          SizedBox(
                            width: Screen.setWidth(4),
                          ),
                          Text(
                              thinkData!.thinkLikeType! <= 999
                                  ? thinkData!.thinkLikeType!
                                  .toString()
                                  : thinkData!.thinkLikeType! >= 10000
                                  ? '${thinkData!.thinkLikeType! ~/ 10000}w+'
                                  : '${thinkData!.thinkLikeType! ~/ 1000}k+',
                              style: TextStyle(
                                  fontSize: 14,
                                  color: this.isLike
                                      ? ColorConfig.ThemeColor
                                      : ColorConfig
                                      .WhiteObsBackColor)),
                          SizedBox(
                            width: Screen.setWidth(4),
                          ),
                          GestureDetector(
                            onTap: () {
                              likeThisThink();
                            },
                            child: ScaleTransition(
                              scale: _iconAnimation,
                              child: this.isLike
                                  ? Icon(
                                CupertinoIcons.heart_fill,
                                size: 25,
                                color: ColorConfig.ThemeColor,
                              )
                                  : Icon(
                                CupertinoIcons.heart,
                                size: 25,
                                color: ColorConfig
                                    .WhiteObsBackColor,
                              ),
                            ),
                          )
                        ],
                      )
                    ],
                  ),
                ),
              ),
            ),
            Positioned(
              top: Screen.setHeight(15),
              right: Screen.setWidth(15),
              child: Container(
                decoration: BoxDecoration(
                    color:
                    thinkCategoryStatus[thinkData!.thinkCategory!]
                    ['color'],
                    borderRadius: BorderRadius.all(Radius.circular(5))),
                width: Screen.setWidth(35),
                height: Screen.setHeight(20),
                child: Center(
                  child: Text(
                    thinkCategoryStatus[thinkData!.thinkCategory!]
                    ['value'],
                    style: TextStyle(fontSize: 12, color: Colors.white),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    )
        : GestureDetector(
      onTap: (){
        if(thinkData!.thinkCategory != 1){
          Modular.to.pushNamed('/thinkInfo/${thinkData!.id}/${thinkData!.thinkCategory}');
        }
      },
      child: Container(
        child: Column(
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                  child: CachedNetworkImage(
                    imageUrl: thinkData!.thinkIndexImageUrl!,
                    fit: BoxFit.cover,
                    width: (Screen.width(Config.context) - 12) / 2,
                    errorWidget: (context, url, error) =>
                    new Icon(Icons.error),
                    placeholder: (context, url) => Container(
                      width: Screen.setWidth(60),
                      height: Screen.setWidth(60),
                      child: Center(
                        child: CircularProgressIndicator(),
                      ),
                    ),
                  ),
                ),
                Positioned(
                  top: Screen.setHeight(15),
                  right: Screen.setWidth(15),
                  child: Container(
                    decoration: BoxDecoration(
                        color:
                        thinkCategoryStatus[thinkData!.thinkCategory!]
                        ['color'],
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    width: Screen.setWidth(35),
                    height: Screen.setHeight(20),
                    child: Center(
                      child: Text(
                        thinkCategoryStatus[thinkData!.thinkCategory!]
                        ['value'],
                        style: TextStyle(fontSize: 12, color: Colors.white),
                      ),
                    ),
                  ),
                )
              ],
            ),
            Container(
              child: Container(
                padding: EdgeInsets.fromLTRB(10, 4, 10, 6),
                height: Screen.setHeight(70),
                width: (Screen.width(Config.context) - 12) / 2,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                            child: Container(
                              child: Text(
                                thinkData!.thinkTitle!,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 17,
                                    color: Colors.black87,
                                    fontWeight: FontWeight.w600),
                              ),
                            )),
                        GestureDetector(
                          onTap: () async {
                            await showDialog(
                                context: context,
                                builder: (context) {
                                  return SimpleDialog(
                                    titlePadding: EdgeInsets.all(15),
                                    contentPadding: EdgeInsets.all(15),
                                    title: Container(
                                      alignment: Alignment.centerLeft,
                                      child: Row(
                                        children: [
                                          Icon(Icons.touch_app,size: 30,color: ColorConfig.ThemeColor,),
                                          SizedBox(width: 5,),
                                          Text("请选择操作",style: TextStyle(fontSize: 17),)
                                        ],
                                      ),
                                    ),
                                    children: <Widget>[
                                      TextButton(
                                          child: Text("保存到相册",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                          onPressed: () async {
                                            Navigator.of(context).pop();
                                            await saveGallery(thinkData!.thinkIndexImageUrl!
                                            );
                                          }
                                      ),
                                      TextButton(
                                          child: Text("收藏",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                          onPressed: () async {
                                            Navigator.of(context).pop();
                                            await collectionThisThink(
                                            );
                                          }
                                      ),
                                      TextButton(
                                          child: Text("分享",style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16),),
                                          onPressed: () async {
                                            Navigator.of(context).pop();
                                            await shareImg(
                                            );
                                          }
                                      ),

                                    ],
                                  );
                                }
                            );
                          },
                          child: Icon(
                            Icons.more_vert,
                            color: ColorConfig.BlackObsBackColor,
                            size: 20,
                          ),
                        )
                      ],
                    ),
                    thinkData!.thinkCategory!=0
                        ? Row(
                      children: [
                        ClipOval(
                          child: GestureDetector(
                            onTap: () {
                              print(thinkData!.id!);
                            },
                            child: CachedNetworkImage(
                              imageUrl: thinkData!.thinkUserImage!,
                              fit: BoxFit.cover,
                              width: Screen.setWidth(28),
                              height: Screen.setWidth(28),
                              errorWidget: (context, url, error) =>
                              new Icon(Icons.error),
                              placeholder: (context, url) =>
                                  Container(
                                    width: Screen.setWidth(20),
                                    height: Screen.setWidth(20),
                                    child: Center(
                                      child: CircularProgressIndicator(),
                                    ),
                                  ),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: Screen.setWidth(4),
                        ),
                        Expanded(
                          child: Text(
                            thinkData!.thinkCountry!.name! +
                                '-' +
                                thinkData!.thinkTimes!,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: 13,
                                color: ColorConfig.BlackObsBackColor),
                          ),
                        ),
                        SizedBox(
                          width: Screen.setWidth(4),
                        ),
                        Text(
                            thinkData!.thinkLikeType! <= 999
                                ? thinkData!.thinkLikeType!.toString()
                                : thinkData!.thinkLikeType! >= 10000
                                ? '${thinkData!.thinkLikeType! ~/ 10000}w+'
                                : '${thinkData!.thinkLikeType! ~/ 1000}k+',
                            style: TextStyle(
                                fontSize: 14,
                                color: this.isLike
                                    ? ColorConfig.ThemeColor
                                    : ColorConfig.BlackObsBackColor)),
                        SizedBox(
                          width: Screen.setWidth(4),
                        ),
                        GestureDetector(
                          onTap: () {
                            likeThisThink();
                          },
                          child: ScaleTransition(
                            scale: _iconAnimation,
                            child: this.isLike
                                ? Icon(
                              CupertinoIcons.heart_fill,
                              size: 25,
                              color: ColorConfig.ThemeColor,
                            )
                                : Icon(
                              CupertinoIcons.heart,
                              size: 25,
                              color:
                              ColorConfig.BlackObsBackColor,
                            ),
                          ),
                        )
                      ],
                    )
                        : Row(
                      children: [
                        Expanded(
                          child: Text(
                            thinkData!.thinkCountry!.name! +
                                '-' +
                                thinkData!.thinkTimes!,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: 14,
                                color: ColorConfig.BlackObsBackColor),
                          ),
                        ),
                        SizedBox(
                          width: Screen.setWidth(4),
                        ),
                        Text(
                            thinkData!.thinkLikeType! <= 999
                                ? thinkData!.thinkLikeType!.toString()
                                : thinkData!.thinkLikeType! >= 10000
                                ? '${thinkData!.thinkLikeType! ~/ 10000}w+'
                                : '${thinkData!.thinkLikeType! ~/ 1000}k+',
                            style: TextStyle(
                                fontSize: 14,
                                color: this.isLike
                                    ? ColorConfig.ThemeColor
                                    : ColorConfig.BlackObsBackColor)),
                        SizedBox(
                          width: Screen.setWidth(4),
                        ),
                        GestureDetector(
                          onTap: () {
                            likeThisThink();
                          },
                          child: ScaleTransition(
                            scale: _iconAnimation,
                            child: this.isLike
                                ? Icon(
                              CupertinoIcons.heart_fill,
                              size: 25,
                              color: ColorConfig.ThemeColor,
                            )
                                : Icon(
                              CupertinoIcons.heart,
                              size: 25,
                              color:
                              ColorConfig.BlackObsBackColor,
                            ),
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

List<Map<String, dynamic>> thinkCategoryStatus = [
  {"color": ColorConfig.ThemeColor, "value": '事件'},
  {"color": Colors.blue, "value": '人物'},
  {"color": Colors.purple, "value": '画作'},
  {"color": Colors.yellow, "value": '古籍'}
];
